
module(...,package.seeall)

require"http"

local bTimeSynced

--[[
local tSaleUserid = 
{
    ["陈玺"] = "ChenXi",
    ["陈媛媛"] = "qy01fa77634e50af0028af123245",
    ["何春梅"] = "HeChunMei",
    ["何晓洪"] = "HeXiaoHong",
    ["王奇"] = "WangQi",
    ["旷文飞"] = "KuangWenFei",
    ["李武"] = "LiWu",
    ["毛宇"] = "MaoYu",
    ["陆相成"] = "qy01d177d94e55af002875a3ea43",
    ["秦莉蓉"] = "QinLiRong",
    ["王世茹"] = "WangShiRu",    
}
]]

local failCnt = 0

local function proc(beginDate)
    local tRegion = {"华南销售区域","华东销售区域","线上销售区域","销售VP","非销售部门"}
    
    local tSaleCustomer =
    {
        --totalGroup存储最近几天，每天的客户群总数表
        --curDateActiveGroup存储最近几天，每天的活跃群数
        --curDateNewGroup存储最近几天，每天的新增群数
        --索引1表示前1天，2表示前2天，3表示前3天，4表示......
        ["ChenXi"] = {name="陈    玺", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["qy01fa77634e50af0028af123245"] = {name="陈媛媛", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["HeChunMei"] = {name="何春梅", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["ShuJie"] = {name="舒    洁", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["BaoLi"] = {name="鲍    丽", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["ZhouZhou"] = {name="周    伟", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        --["HeZhouluatMengMeng"] = {name="周  伟-2", region=tRegion[3], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["HeXiaoHong"] = {name="何晓洪", region=tRegion[2], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        --["WangQi"] = {name="王    奇", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        --["KuangWenFei"] = {name="旷文飞", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        --["LiWu"] = {name="李    武", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["YangFengZhen"] = {name="杨凤珍", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["MaoYu"] = {name="毛    宇", region=tRegion[2], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["qy01d177d94e55af002875a3ea43"] = {name="陆相成", region=tRegion[4],totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["QinLiRong"] = {name="秦莉蓉", region=tRegion[2], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["WangShiRu"] = {name="王世茹", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        --["YuLiHua"] = {name="喻利华", region=tRegion[1], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["QinPeng"] = {name="秦    鹏", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["JinYi"] = {name="金    艺", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["LiuLeAn"] = {name="刘乐安", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["LiWeiQiang"] = {name="李炜镪", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["ZhuPingJun"] = {name="祝平军", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["WangLei"] = {name="王    磊", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["monitor"] = {name="小助手", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
        ["YanGuoLiang"] = {name="闫国梁", region=tRegion[5], totalGroup={}, curDateActiveGroup={}, curDateNewGroup={}},
    }
    
    local userIdList = {}
    for k,v in pairs(tSaleCustomer) do
        table.insert(userIdList,k)
    end
    
    --查询日期的起始时间
    local beginTm = os.time({year=beginDate.year, month=beginDate.month, day=beginDate.day, hour=0, min=0, sec=0})
    
    --最近几天活跃客户群数量
    local nCurDateActiveTotalCnt = {}   
    --最近几天新增客户群数量
    local nCurDateNewCnt = {}     
    --最近几天截止当日客户群总数
    local nTotalCnt = {} 
    
    --循环查询保存最近几天的数据
    local totalDays = 5
    local curIndex = 1 --1表示当日，2表示昨天，3表示前天，4表示......
    while curIndex<=totalDays do
        local beginDate = os.date("*t",beginTm)
        log.info("saleCustomer.beginDate",beginDate.year,beginDate.month,beginDate.day,beginDate.hour,beginDate.min,beginDate.sec)
        http.request("POST",
            "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token="..nvm.get("accessToken"),
            nil,                            
            {
                ["Content-Type"] = "application/json",
            },
            json.encode(
                {
                    day_begin_time=beginTm,
                    owner_filter={
                        userid_list = userIdList
                    },
                }
            ),
            30000,
            function (result,statusCode,head,body)
                log.info("saleCustomer.rsp",result,statusCode,head,body)
                sys.publish("GET_SALE_CUSTOMER_RSP",result,statusCode,head,body)
            end)                    
        
        local _,result,statusCode,head,body = sys.waitUntil("GET_SALE_CUSTOMER_RSP")
        
        if result and statusCode=="200" and body and body~="" then
            local tJsonData,result,errInfo = json.decode(body)
            if result and type(tJsonData)=="table" then
                if tJsonData.errcode==0 and type(tJsonData.items)=="table" and tJsonData.total>0 then
                    log.info("saleCustomer.rsp success")                    
                    
                    for k,v in pairs(tJsonData.items) do
                        tSaleCustomer[v.owner].totalGroup[curIndex] = v.data.chat_total
                        nTotalCnt[curIndex] = (nTotalCnt[curIndex] or 0)+v.data.chat_total
                        
                        tSaleCustomer[v.owner].curDateActiveGroup[curIndex] = v.data.chat_has_msg
                        nCurDateActiveTotalCnt[curIndex] = (nCurDateActiveTotalCnt[curIndex] or 0)+v.data.chat_has_msg
                        
                        tSaleCustomer[v.owner].curDateNewGroup[curIndex] = v.data.new_chat_cnt
                        nCurDateNewCnt[curIndex] = (nCurDateNewCnt[curIndex] or 0)+v.data.new_chat_cnt                        
                    end 
                    
                    curIndex = curIndex+1
                    beginTm = os.time(os.date("*t",beginTm-24*3600))
                    failCnt = 0
                elseif tJsonData.errcode==40014 then
                    sys.publish("ACCESS_TOKEN_REQUEST")
                    failCnt = failCnt+1
                --无效的用户
                elseif tJsonData.errcode==40003 then
                    
                else
                    log.warn("saleCustomer.rsp format error") 
                    failCnt = failCnt+1                
                end                        
            else
                log.warn("saleCustomer.rsp json.decode error",errInfo)
                failCnt = failCnt+1
            end
        else
            failCnt = failCnt+1
        end
        
        if failCnt>=3 then sys.restart("saleCustomer.FAIL_CNT_ERROR") end      
        
    end
    
    
    --解析最近几天的数据，生成markdown格式数据
    
    --以销售区域为主键重构数据表（索引值为数字，方便排序）
    local tRegionData = {}
    for i=1,#tRegion do
        tRegionData[i] = {region=tRegion[i],totalGroup={},curDateActiveGroup={},curDateNewGroup={},eachSalesData={}}
        for k,v in pairs(tSaleCustomer) do
            if v.region==tRegion[i] then
                table.insert(tRegionData[i].eachSalesData, {name=v.name,totalGroup=v.totalGroup,curDateActiveGroup=v.curDateActiveGroup,curDateNewGroup=v.curDateNewGroup})
                for j=1,totalDays do
                    tRegionData[i].totalGroup[j] = (tRegionData[i].totalGroup[j] or 0)+v.totalGroup[j]
                    tRegionData[i].curDateActiveGroup[j] = (tRegionData[i].curDateActiveGroup[j] or 0)+v.curDateActiveGroup[j]
                    tRegionData[i].curDateNewGroup[j] = (tRegionData[i].curDateNewGroup[j] or 0)+v.curDateNewGroup[j]
                end
            end
        end
        table.sort(tRegionData[i].eachSalesData,function(a,b)
            local result = false
            if a.curDateActiveGroup[1]>b.curDateActiveGroup[1] then
                result = true
            end
            return result
        end)
    end
    
    --以销售姓名为主键重构数据表（索引值为数字，方便排序）
    local tSalesData = {}
    for k,v in pairs(tSaleCustomer) do
        table.insert(tSalesData,v)
    end
    
    local mdData = "# 企业微信小群 "..string.format("%04d-%02d-%02d",beginDate.year,beginDate.month,beginDate.day).. " 日报\r\n"
    
    local function alignTableConcat(t,width,sep)
        local concatStr = ""
        for i=1,#t do
            concatStr = concatStr..string.rep(" ",(width-string.len(t[i]))*2)..t[i]..(i==#t and "" or sep)
        end
        return concatStr
    end
    
    --活跃客户群    
    mdData = mdData.."## 一、当日活跃客户群数量("..nCurDateActiveTotalCnt[1]..")\r\n"
    for i=1,#tRegionData do
        mdData = mdData.."### ("..i..")"..tRegionData[i].region.."("..tRegionData[i].curDateActiveGroup[1]..")\r\n"
        for k,v in pairs(tRegionData[i].eachSalesData) do
            mdData = mdData..""..v.name..": "..alignTableConcat(v.curDateActiveGroup,2," ").."\r\n"
        end
    end
    
    mdData = mdData.."### (6)合宙全部("..nCurDateActiveTotalCnt[1]..")\r\n"
    mdData = mdData.."合  计: "..alignTableConcat(nCurDateActiveTotalCnt,3," ").."\r\n"
    
    
    
    mdData = mdData.."### (7)个人排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tSalesData,function(a,b)
            local result = false
            if a.curDateActiveGroup[i]>b.curDateActiveGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tSalesData do
            if not string.match(tSalesData[j].region,"非销售") then
                mdData = mdData..seq.."."..tSalesData[j].name.."("..tSalesData[j].curDateActiveGroup[i]..");  "
                if seq%4==0 or j==#tSalesData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end
        mdData = mdData.."\r\n"
    end
    
    mdData = mdData.."### (8)区域排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tRegionData,function(a,b)
            local result = false
            if a.curDateActiveGroup[i]>b.curDateActiveGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tRegionData do
            if not string.match(tRegionData[j].region,"非销售") then
                mdData = mdData..seq.."."..tRegionData[j].region.."("..tRegionData[j].curDateActiveGroup[i]..");  "
                if seq%4==0 or j==#tRegionData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end        
        mdData = mdData.."\r\n"
    end
    
    log.info("saleCustomer.proc",mdData)
    
    mdData = mdData.."\r\n".."<@zhutianhua><@qy01d177d94e55af002875a3ea43>"        
                
                
                
    sys.publish("RPT_WECHAR_ROBOT_REQUEST",mdData)
    --sys.timerStart(sys.publish,1000,"RPT_WECHAR_ROBOT_IND",true)
    _,result = sys.waitUntil("RPT_WECHAR_ROBOT_IND")
    if result then
        
    end
    
    local function getRegionIndex(region)
        for i=1,#tRegion do
            if tRegion[i]==region then return i end
        end
    end
    
    
    table.sort(tRegionData,function(a,b)
        local result = false
        if getRegionIndex(a.region)<getRegionIndex(b.region) then
            result = true
        end
        return result
    end)
    
    --新增客户群    
    mdData = "## 二、当日新增客户群数量("..nCurDateNewCnt[1]..")\r\n"
    for i=1,#tRegionData do
        mdData = mdData.."### ("..i..")"..tRegionData[i].region.."("..tRegionData[i].curDateNewGroup[1]..")\r\n"
        table.sort(tRegionData[i].eachSalesData,function(a,b)
            local result = false
            if a.curDateNewGroup[1]>b.curDateNewGroup[1] then
                result = true
            end
            return result
        end)
        for k,v in pairs(tRegionData[i].eachSalesData) do
            mdData = mdData..""..v.name..": "..alignTableConcat(v.curDateNewGroup,2," ").."\r\n"
        end
    end
    
    mdData = mdData.."### (6)合宙全部("..nCurDateNewCnt[1]..")\r\n"
    mdData = mdData.."合  计: "..alignTableConcat(nCurDateNewCnt,3," ").."\r\n"
    
    
    
    mdData = mdData.."### (7)个人排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tSalesData,function(a,b)
            local result = false
            if a.curDateNewGroup[i]>b.curDateNewGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tSalesData do
            if not string.match(tSalesData[j].region,"非销售") then
                mdData = mdData..seq.."."..tSalesData[j].name.."("..tSalesData[j].curDateNewGroup[i]..");  "
                if seq%4==0 or j==#tSalesData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end
        mdData = mdData.."\r\n"
    end
    
    mdData = mdData.."### (8)区域排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tRegionData,function(a,b)
            local result = false
            if a.curDateNewGroup[i]>b.curDateNewGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tRegionData do
            if not string.match(tRegionData[j].region,"非销售") then
                mdData = mdData..seq.."."..tRegionData[j].region.."("..tRegionData[j].curDateNewGroup[i]..");  "
                if seq%4==0 or j==#tRegionData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end        
        mdData = mdData.."\r\n"
    end
    
    
    log.info("saleCustomer.proc",mdData)
    
    mdData = mdData.."\r\n".."<@zhutianhua><@qy01d177d94e55af002875a3ea43>"           
                
                
                
    sys.publish("RPT_WECHAR_ROBOT_REQUEST",mdData)
    --sys.timerStart(sys.publish,1000,"RPT_WECHAR_ROBOT_IND",true)
    _,result = sys.waitUntil("RPT_WECHAR_ROBOT_IND")
    if result then
        
    end

    table.sort(tRegionData,function(a,b)
        local result = false
        if getRegionIndex(a.region)<getRegionIndex(b.region) then
            result = true
        end
        return result
    end)

    --客户群总数    
    mdData = "## 三、截至当日客户群总数量("..nTotalCnt[1]..")\r\n"
    for i=1,#tRegionData do
        mdData = mdData.."### ("..i..")"..tRegionData[i].region.."("..tRegionData[i].totalGroup[1]..")\r\n"
        table.sort(tRegionData[i].eachSalesData,function(a,b)
            local result = false
            if a.totalGroup[1]>b.totalGroup[1] then
                result = true
            end
            return result
        end)
        for k,v in pairs(tRegionData[i].eachSalesData) do
            mdData = mdData..""..v.name..": "..alignTableConcat(v.totalGroup,3," ").."\r\n"
        end
    end
    
    mdData = mdData.."### (6)合宙全部("..nTotalCnt[1]..")\r\n"
    mdData = mdData.."合  计: "..alignTableConcat(nTotalCnt,3," ").."\r\n"
    
    
    
    mdData = mdData.."### (7)个人排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tSalesData,function(a,b)
            local result = false
            if a.totalGroup[i]>b.totalGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tSalesData do
            if not string.match(tSalesData[j].region,"非销售") then
                mdData = mdData..seq.."."..tSalesData[j].name.."("..tSalesData[j].totalGroup[i]..");  "
                if seq%4==0 or j==#tSalesData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end
        mdData = mdData.."\r\n"
    end
    
    mdData = mdData.."### (8)区域排名\r\n"
    for i=1,totalDays do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tRegionData,function(a,b)
            local result = false
            if a.totalGroup[i]>b.totalGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tRegionData do
            if not string.match(tRegionData[j].region,"非销售") then
                mdData = mdData..seq.."."..tRegionData[j].region.."("..tRegionData[j].totalGroup[i]..");  "
                if seq%4==0 or j==#tRegionData then
                    mdData = mdData.."\r\n"
                end
                seq = seq+1
            end
        end        
        mdData = mdData.."\r\n"
    end
    
    
    log.info("saleCustomer.proc",mdData)
    
    mdData = mdData.."\r\n".."<@zhutianhua><@qy01d177d94e55af002875a3ea43>"           
                
                
                
    sys.publish("RPT_WECHAR_ROBOT_REQUEST",mdData)
    --sys.timerStart(sys.publish,1000,"RPT_WECHAR_ROBOT_IND",true)
    _,result = sys.waitUntil("RPT_WECHAR_ROBOT_IND")
    if result then
        
    end
    
    
    --个人排名红绿榜    
    mdData = "## 四、个人排名红绿榜\r\n"
    mdData = mdData.."### (1)当日活跃客户数量\r\n"
    table.sort(tSalesData,function(a,b)
        local result = false
        if (a.curDateActiveGroup[1]-a.curDateActiveGroup[2])>(b.curDateActiveGroup[1]-b.curDateActiveGroup[2]) then
            result = true
        end
        return result
    end)
    
    mdData = mdData.."##### 红榜前三名\r\n"
    local matchCnt = 0
    --while true do
    for i=1,#tSalesData do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].curDateActiveGroup[1]-tSalesData[i].curDateActiveGroup[2]).."\r\n"
            --log.info("mdData.len",mdData.len())
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end
    
    mdData = mdData.."##### 绿榜前三名\r\n"
    matchCnt = 0
    --while true do
    for i=#tSalesData,1,-1 do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].curDateActiveGroup[1]-tSalesData[i].curDateActiveGroup[2]).."\r\n"
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end

    
    mdData = mdData.."### (2)当日新增客户群数量\r\n"
    table.sort(tSalesData,function(a,b)
        local result = false
        if (a.curDateNewGroup[1]-a.curDateNewGroup[2])>(b.curDateNewGroup[1]-b.curDateNewGroup[2]) then
            result = true
        end
        return result
    end)
    mdData = mdData.."##### 红榜前三名\r\n"
    local matchCnt = 0
    --while true do
    for i=1,#tSalesData do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].curDateNewGroup[1]-tSalesData[i].curDateNewGroup[2]).."\r\n"
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end
    
    mdData = mdData.."##### 绿榜前三名\r\n"
    matchCnt = 0
    --while true do
    for i=#tSalesData,1,-1 do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].curDateNewGroup[1]-tSalesData[i].curDateNewGroup[2]).."\r\n"
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end
    
    mdData = mdData.."### (3)截止当日客户群总数量\r\n"
    table.sort(tSalesData,function(a,b)
        local result = false
        if (a.totalGroup[1]-a.totalGroup[2])>(b.totalGroup[1]-b.totalGroup[2]) then
            result = true
        end
        return result
    end)
    mdData = mdData.."##### 红榜前三名\r\n"
    local matchCnt = 0
    --while true do
    for i=1,#tSalesData do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].totalGroup[1]-tSalesData[i].totalGroup[2]).."\r\n"
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end
    
    mdData = mdData.."##### 绿榜前三名\r\n"
    matchCnt = 0
    --while true do
    for i=#tSalesData,1,-1 do
        if not string.match(tSalesData[i].region,"非销售") then
            mdData = mdData..tSalesData[i].name..":"..(tSalesData[i].totalGroup[1]-tSalesData[i].totalGroup[2]).."\r\n"
            matchCnt = matchCnt+1
            if matchCnt==3 then break end
        end
    end
    --end
    
    log.info("saleCustomer.proc",mdData)
    
    mdData = mdData.."\r\n".."<@zhutianhua><@qy01d177d94e55af002875a3ea43>"
    
    sys.publish("RPT_WECHAR_ROBOT_REQUEST",mdData)
    --sys.timerStart(sys.publish,1000,"RPT_WECHAR_ROBOT_IND",true)
    _,result = sys.waitUntil("RPT_WECHAR_ROBOT_IND")
    if result then
        
    end
    
    
    --销售部客户群总数排名   
    mdData = "## 五、销售部客户群总数排名\r\n"
    for i=1,1 do
        --mdData = mdData.."> 前"..i.."天: "
        local curDate = os.date("*t",os.time(beginDate)-(i-1)*24*3600)
        mdData = mdData..""..string.format("%04d-%02d-%02d",curDate.year,curDate.month,curDate.day)..": \r\n"
        --排序某天的数据排序
        table.sort(tSalesData,function(a,b)
            local result = false
            if a.totalGroup[i]>b.totalGroup[i] then
                result = true
            end
            return result
        end)
        local seq = 1
        for j=1,#tSalesData do
            if not string.match(tSalesData[j].region,"非销售") and not string.match(tSalesData[j].region,"销售VP") then
                local substract = tSalesData[j].totalGroup[i]-tSalesData[j].totalGroup[i+1]
                local tag = (substract<0) and "下降" or "上升"
                substract = (substract<0) and (-substract) or substract
                mdData = mdData..string.format("%02d",seq).."."..tSalesData[j].name.."，当日"..tSalesData[j].totalGroup[i].."，相对前日"..tag..substract.."个\r\n"
                seq = seq+1
            end
        end
        mdData = mdData.."\r\n"
    end
    
    log.info("saleCustomer.proc",mdData)
    
    mdData = mdData.."\r\n".."<@zhutianhua><@qy01d177d94e55af002875a3ea43>"           
                
                
                
    sys.publish("RPT_WECHAR_ROBOT_REQUEST",mdData)
    --sys.timerStart(sys.publish,1000,"RPT_WECHAR_ROBOT_IND",true)
    _,result = sys.waitUntil("RPT_WECHAR_ROBOT_IND")
    if result then
        nvm.set("lastRptTm",os.time({year=beginDate.year, month=beginDate.month, day=beginDate.day, hour=0, min=0, sec=0}))
    end
end


function request()
    sys.taskInit(
        function ()
            local retryCnt = 0
            while true do
                if not socket.isReady() then
                    retryCnt = 0
                    --等待网络环境准备就绪，超时时间是5分钟
                    sys.waitUntil("IP_READY_IND",300000)
                end
                
                if not bTimeSynced then
                    sys.waitUntil("TIME_SYNC_SUCCESS_IND")
                end

                if nvm.get("accessToken")=="" then
                    sys.waitUntil("ACCESS_TOKEN_SUCCESS_IND")
                end
                
                if socket.isReady() then
                    local lastRptTm = nvm.get("lastRptTm")
                    
                    log.info("salesCustomer.lastRptTm",lastRptTm,string.format)
                    
                    --nil表示从来没有上报过，仅从当前运行的前一天开始上报
                    if lastRptTm==nil then
                        proc(os.date("*t",(os.time()-24*3600)))
                    --其他时间戳表示上次上报成功的起始时间戳（某个日期的0时0分0秒），需要上报的日期范围：从上次上报成功的时间戳开始的后一天算起，一直到昨天
                    else
                        local curDate = os.date("*t")
                        local curTm = os.time()
                        
                        local beginHour = 6
                        local beginMin = 0
                        
                        while true do
                            local beginTm = nvm.get("lastRptTm")+24*3600
                            local beginDate = os.date("*t",beginTm+24*3600+beginHour*3600+beginMin*60)
                            log.info("saleCustomers.beginTm",beginTm+24*3600+beginHour*3600+beginMin*60,curTm,
                                string.format("%04d-%02d-%02d %02d:%02d:%02d",beginDate.year,beginDate.month,beginDate.day,beginDate.hour,beginDate.min,beginDate.sec),
                                string.format("%04d-%02d-%02d %02d:%02d:%02d",curDate.year,curDate.month,curDate.day,curDate.hour,curDate.min,curDate.sec))
                            if beginTm+24*3600+beginHour*3600+beginMin*60<curTm then
                                proc(os.date("*t",beginTm))
                            else
                                break
                            end
                        end
                    end
                    
                    sys.wait(52000)
                else
                    --进入飞行模式，20秒之后，退出飞行模式
                    net.switchFly(true)
                    sys.wait(20000)
                    net.switchFly(false)
                end
            end
        end
    )
end


sys.subscribe("TIME_SYNC_SUCCESS_IND",function()
    bTimeSynced = true
end)

request()
--sys.subscribe("ACCESS_TOKEN_SUCCESS_IND",request)

--测试代码:https://tool.lu/timestamp/
--nvm.set("lastRptTm",1621180800)
--nvm.set("lastRptTm",nil)

